package edu.interceptor;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sun.corba.se.impl.oa.toa.TOA;
import edu.annotations.LoginRequired;
import edu.common.CommonResult;
import edu.utils.JwtUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 检查所有接收到的请求是否携带 合法的 token令牌
 * 可以预防如下情况
 * 1. 请求中没有token => 用户没有登陆
 * 2. 请求中错误的token => 恶意请求
 * 3. 请求中token已过期 => 用户登录态已失效
 */
@Configuration
public class TokenInterceptor extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                boolean isPass = true;
                if (!(handler instanceof HandlerMethod)) {
                    return true;
                }
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                if (method.isAnnotationPresent(LoginRequired.class)) {
                    String token = request.getHeader("token");
                    if (StringUtil.isNullOrEmpty(token) || !JwtUtil.verity(token)) {
                        CommonResult<Object> result = new CommonResult<>(100);
                        JSONObject jsonObject = JSONUtil.parseObj(result);
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        out.write(jsonObject.toString());
                        out.flush();
                        out.close();
                        isPass = false;
                    }
                }
                return isPass;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}
